package com.du.ichat.utils;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.os.Environment;
import android.support.annotation.RequiresApi;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class Utils {
    private static String[] PERMISSION = new String[]{Manifest.permission.READ_PHONE_STATE , Manifest.permission.WRITE_EXTERNAL_STORAGE ,Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA
    };

    public static File avatarPath = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getPath(),
            "cutcamera.png");

    @SuppressLint("WrongConstant")
    @RequiresApi(api = Build.VERSION_CODES.M)
    public static void copyDefaultAvatarFile(Activity context) {
        if(context.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != 0){
            context.requestPermissions(PERMISSION , 101);
            return;
        }
        InputStream is = null;
        FileOutputStream fos = null;
        try {
            File defaultAvatar = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getPath(),
                    "cutcamera.png");
            if(defaultAvatar.exists()){
                defaultAvatar.delete();
            }

            is = context.getAssets().open("default_avatar.jpg");
            fos = new FileOutputStream(defaultAvatar);
            String temp = null;
            byte[] buffer = new byte[1024 * 2];
            int byteRead = 0;
            while ((byteRead = is.read(buffer)) > 0){
                fos.write(buffer , 0 , byteRead);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(is != null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fos != null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        Log.e("tag","copy default avatar success");
    }
}
